package com.xaicode.template.gendata.common;

import org.apache.commons.io.IOUtils;
import org.springframework.boot.system.ApplicationHome;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

/**
 * @author Locker xaicode@sina.com
 * @version 1.0
 * @date 2022/5/24 0024 20:16
 */
public class ConfigUtil {

    public static String loadJsonFile(String fileName) {
        String filePath = getJarDir() + "/" + fileName;
        File file = new File(filePath);

        InputStream is = null;
        try {
            if (file.exists()) {
                is = new FileInputStream(file);
            } else {
                is = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
            }

            return IOUtils.toString(is, StandardCharsets.UTF_8.toString());
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("config file " + fileName + " fail");
        }
    }

    public static String getJarDir() {
        File file = getJarFile();
        return null == file ? null : file.getParent();
    }

    private static File getJarFile() {
        ApplicationHome home = new ApplicationHome(ConfigUtil.class);
        return home.getSource();
    }

}
